package com.yangsen.oss;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.jfinal.kit.PropKit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class OSSService {
    private static final Logger log = LogManager.getLogger(OSSService.class);
    private static String endpoint = "oss-cn-beijing.aliyuncs.com";

    private static String accessKeyId = PropKit.get("accessKeyId");
    private static String accessKeySecret = PropKit.get("accessKeySecret");

    private static String bucketName = "senyun";

    /*
    * 上传文件
    * */
    public boolean upload(String key, File file, String path) {

        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {


            key = path + key;
            UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, key);
            uploadFileRequest.setUploadFile(file.getPath());
            uploadFileRequest.setTaskNum(5);
            uploadFileRequest.setPartSize(1024 * 1024);
            uploadFileRequest.setEnableCheckpoint(true);
            oss.uploadFile(uploadFileRequest);

//            oss.putObject(new PutObjectRequest(bucketName, key, file));简单上传
            return oss.doesObjectExist(bucketName, key);
        } catch (Throwable e) {
            log.catching(e);
            return false;
        } finally {
            oss.shutdown();
        }
    }

    /*
    * 创建文件夹
    *
    * */
    public boolean createFolder(String username, String folderName) {

        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            final String keySuffixWithSlash = username + "/" + folderName + "/";
            oss.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
            return oss.doesObjectExist(bucketName, keySuffixWithSlash);
        } catch (RuntimeException e) {
            log.catching(e);
            return false;
        } finally {
            oss.shutdown();
        }
    }

    /*
    * 返回文件列表
    * */
    public String listObject(String folderName) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//        System.out.println("2");
        try {
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            listObjectsRequest.setDelimiter("/");
            listObjectsRequest.setPrefix(folderName);
            ObjectListing listing = oss.listObjects(listObjectsRequest);
            List<ossSimpleObject> data = new ArrayList<ossSimpleObject>();
            for (OSSObjectSummary ossObjectSummary : listing.getObjectSummaries()) {
                if (!ossObjectSummary.getKey().equals(folderName)) {
                    data.add(new ossSimpleObject(folderName, ossObjectSummary.getKey(), SizeConverter.BTrim.convert((float) ossObjectSummary.getSize()), ossObjectSummary.getLastModified()));
                }
            }
            for (String commonPrefix : listing.getCommonPrefixes()) {
                data.add(new ossSimpleObject(folderName, commonPrefix, null, null));
            }
//            System.out.println(JSON.toJSON(data));
//            System.out.println(JSON.toJSON(new layuiTableData(0, "", 1000, data)));
            return JSON.toJSONString(new layuiTableData(0, "", 1000, data), SerializerFeature.WriteDateUseDateFormat);
        } catch (RuntimeException e) {
            log.catching(e);
            return null;
        } finally {
            oss.shutdown();
        }
    }


    /*
    * 删除文件
    * */
    public boolean deleteOnly(String key) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        oss.deleteObject(bucketName, key);
        return !oss.doesObjectExist(bucketName, key);
    }

    /*
    * 删除多个文件
    * */
    public boolean deleteMany(List<String> keys) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys);
        deleteObjectsRequest.setQuiet(true);
        DeleteObjectsResult deleteObjectsResult = oss.deleteObjects(deleteObjectsRequest);
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        return deletedObjects.isEmpty();
    }

    public boolean download(String key) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String temp[] = key.split("/");
        try {
            DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, key);
            downloadFileRequest.setTaskNum(10);
            downloadFileRequest.setEnableCheckpoint(true);
            downloadFileRequest.setDownloadFile(temp[temp.length - 1]);
            DownloadFileResult downloadFileResult = oss.downloadFile(downloadFileRequest);
            return downloadFileResult.getObjectMetadata() != null;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return false;
        } finally {
            oss.shutdown();
        }
    }

}
